import { isUndefined, isArray, _pick, reduceToObject, getTodayTS } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import pageMW from "../../middleware/pager";
import Router from "koa-router";
import {
  listActivityItemOfSWithStatsByUserIDAsSpokesman,
  listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsSpokesman,
  listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsFollower,
  listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsInvolver,
  listActivityItemOfU2CWithStatAndOwnerInfosForUserByBrandIDInBrandOwn,
  listActivityItemOfU2CWithStatAndOwnerInfosForUserByStoreIDInStoreOwn,
  getActivityOfU2CWithStatAndOwnerInfoForUser,
} from "../../service/activityService";
import {
  AggsToActivityUserPvCount,
  listAggsToActivityUserPvCounts,
  createActivityUserPvLogMq,
} from "../../service/activityUserPvLogService";
import ActivityProcessStatus, {
  isActivityProcessStatus,
} from "../../bg-enums/activityProcessStatus";
import PageOfC from "../../bg-enums/pageOfC";

const router = new Router();

// 获取品牌主页活动列表
router.get("/usr/activities/brandOwn", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { brandId } = ctx.query;
  let { dateBegin, dateEnd } = ctx.query;
  if (isUndefined(brandId)) {
    ctx.throw(400, "brandId invalid");
  }

  if (isUndefined(dateBegin) || isUndefined(dateEnd)) {
    const { tsBegin, tsEnd } = getTodayTS();
    if (isUndefined(dateBegin)) {
      dateBegin = tsBegin;
    }
    if (isUndefined(dateEnd)) {
      dateEnd = tsEnd;
    }
  }

  const {
    total,
    items,
  } = await listActivityItemOfU2CWithStatAndOwnerInfosForUserByBrandIDInBrandOwn(
    {
      brandId,
      dateBegin: Number(dateBegin),
      dateEnd: Number(dateEnd),
    },
    {
      limit,
      offset,
      ts,
    }
  );

  ctx.body = {
    total,
    rows: items,
  };
});


// 获取门店主页活动列表
router.get("/usr/activities/storeOwn", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { storeId } = ctx.query;
  let { dateBegin, dateEnd } = ctx.query;
  if (isUndefined(storeId)) {
    ctx.throw(400, "storeId invalid");
  }

  if (isUndefined(dateBegin) || isUndefined(dateEnd)) {
    const { tsBegin, tsEnd } = getTodayTS();
    if (isUndefined(dateBegin)) {
      dateBegin = tsBegin;
    }
    if (isUndefined(dateEnd)) {
      dateEnd = tsEnd;
    }
  }

  const {
    total,
    items,
  } = await listActivityItemOfU2CWithStatAndOwnerInfosForUserByStoreIDInStoreOwn(
    {
      storeId,
      dateBegin: Number(dateBegin),
      dateEnd: Number(dateEnd),
    },
    {
      limit,
      offset,
      ts,
    }
  );
  
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取用户参与的活动列表
router.get("/usr/activities/involved", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const {
    total,
    items,
  } = await listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsInvolver(
    userId,
    {
      limit,
      offset,
      ts,
    }
  );

  // const activityUserPvCounts = await listAggsToActivityUserPvCounts(
  //   items.map((it) => it.activityId)
  // );
  // const activityUserPvCountsMap = reduceToObject(
  //   activityUserPvCounts,
  //   (o: AggsToActivityUserPvCount) => o.activityId,
  //   (o: AggsToActivityUserPvCount) => o.viewCount
  // );

  ctx.body = {
    total,
    rows: items,
  };
});

// 获取用户首页最新的活动列表(暂时只支持自己)
router.get("/usr/activities/recent", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const {
    total,
    items,
  } = await listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsFollower(
    userId,
    {
      limit,
      offset,
      ts,
    }
  );

  // const activityUserPvCounts = await listAggsToActivityUserPvCounts(
  //   items.map((it) => it.activityId)
  // );
  // const activityUserPvCountsMap = reduceToObject(
  //   activityUserPvCounts,
  //   (o: AggsToActivityUserPvCount) => o.activityId,
  //   (o: AggsToActivityUserPvCount) => o.viewCount
  // );

  ctx.body = {
    total,
    rows: items,
  };
});

// 获取用户代言的活动列表(从我的代言进入,代言人视角)
router.get("/usr/activities/endorsed", pageMW, async (ctx: AppCTX, next) => {
  let { isAll, processStatus, keyword } = ctx.query;
  const { userId, limit, offset, ts } = ctx;
  let arrProcessStatus: ActivityProcessStatus[] = [];
  if (!isUndefined(processStatus)) {
    for (let ps of processStatus.split(",")) {
      if (!isActivityProcessStatus(ps)) {
        ctx.throw(400, "processStatus invalid");
      }
      arrProcessStatus.push(ps);
    }
  }
  const {
    total,
    items,
  } = await listActivityItemOfSWithStatsByUserIDAsSpokesman(
    {
      userId,
      isAll: isAll === "true",
      processStatuses: arrProcessStatus,
      keyword,
    },
    {
      limit,
      offset,
      ts,
    }
  );

  // const activityUserPvCounts = await listAggsToActivityUserPvCounts(
  //   items.map((it) => it.activityId)
  // );
  // const activityUserPvCountsMap = reduceToObject(
  //   activityUserPvCounts,
  //   (o: AggsToActivityUserPvCount) => o.activityId,
  //   (o: AggsToActivityUserPvCount) => o.viewCount
  // );

  ctx.body = {
    total,
    rows: items,
  };
});

// 进入指定用户主页获取他的代言活动列表(普通用户视角+权限)
router.get(
  "/usr/activities/spokesman/:byUserId",
  pageMW,
  async (ctx: AppCTX, next) => {
    let { processStatus, keyword } = ctx.query;
    const { byUserId } = ctx.params;
    const { userId, limit, offset, ts } = ctx;

    const {
      total,
      items,
    } = await listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsSpokesman(
      // userId,
      byUserId,
      {
        limit,
        offset,
        ts,
      }
    );

    // const activityUserPvCounts = await listAggsToActivityUserPvCounts(
    //   items.map((it) => it.activityId)
    // );
    // const activityUserPvCountsMap = reduceToObject(
    //   activityUserPvCounts,
    //   (o: AggsToActivityUserPvCount) => o.activityId,
    //   (o: AggsToActivityUserPvCount) => o.viewCount
    // );

    ctx.body = {
      total,
      rows: items,
    };
  }
);

// 获取活动详情(用户视角)
router.get("/usr/activity/:activityId", async (ctx: AppCTX, next) => {
  const { activityId } = ctx.params;
  const { userId } = ctx;

  let { page } = ctx.query;

  // 创建一条activity_user_pv_log,来推送消息
  if (isUndefined(page)) {
    page = PageOfC.GROUP_BUYING_1_HOME;
  }
  createActivityUserPvLogMq({ userId, activityId, page });

  // 根据activityId获取活动判断是品牌自发活动还是代言人代言的活动
  const activityOfU2C = await getActivityOfU2CWithStatAndOwnerInfoForUser({
    activityId,
    userId,
  });

  // const activityUserPvCounts = await listAggsToActivityUserPvCounts([
  //   activityId,
  // ]);
  // const activityUserPvCountsMap = reduceToObject(
  //   activityUserPvCounts,
  //   (o: AggsToActivityUserPvCount) => o.activityId,
  //   (o: AggsToActivityUserPvCount) => o.viewCount
  // );
  ctx.body = {
    ...activityOfU2C,
  };
});

// 获取活动的购买记录列表
router.get(
  "/usr/activity/:activityId/buyRecords",
  async (ctx: AppCTX, next) => {
    const { activityId } = ctx.params;
    const { userId } = ctx;
    ctx.body = {
      activityId,
      userId,
      buyRecords: [
        {
          orderId: (5123).toString(),
          ordered: Date.now(),
          items: [
            {
              itemInfo: { productName: "商品名称1", keyA: "a2", keyB: "b1" },
              quality: 1,
            },
          ],
        },
        {
          orderId: (5124).toString(),
          ordered: Date.now(),
          items: [
            {
              itemInfo: { productName: "商品名称1", keyA: "a1", keyB: "b1" },
              quality: 1,
            },
          ],
        },
      ],
    };
  }
);

export default router;
